package com.yantong.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.yantong.pojo.OrderProduct;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.AttributedString;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author gaoyuzhe
 * @date 2017/12/18.
 */
public class ImageUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(ImageUtils.class);
    /***
     * 剪裁图片
     *
     * @param file 图片
     * @param x    起点横坐标
     * @param y    纵坐标
     * @param w    长
     * @param h    高
     * @throws IOException
     * @date
     */
    public static BufferedImage cutImage(MultipartFile file, int x, int y, int w, int h, String prefix) {

        Iterator iterator = ImageIO.getImageReadersByFormatName(prefix);
        InputStream in = null;
        ImageInputStream iis = null;
        try {
            ImageReader reader = (ImageReader) iterator.next();
            //转换成输入流
            in = file.getInputStream();
            iis = ImageIO.createImageInputStream(in);
            reader.setInput(iis, true);
            ImageReadParam param = reader.getDefaultReadParam();
            Rectangle rect = new Rectangle(x, y, w, h);
            param.setSourceRegion(rect);
            BufferedImage bi = reader.read(0, param);
            return bi;
        } catch (Exception ignored) {
        }finally {
 			try {
 				if (in != null) {
 					in.close();
 				}
 				if (iis != null) {
 					iis.close();
 				}
			} catch (Exception e) {

				e.printStackTrace();
			}
		}
        return null;
    }

    /***
     * 图片旋转指定角度
     *
     * @param bufferedimage 图像
     * @param degree        角度
     * @return
     * @date
     */
    public static BufferedImage rotateImage(BufferedImage bufferedimage, int degree) {
        int w = bufferedimage.getWidth();
        int h = bufferedimage.getHeight();
        int type = bufferedimage.getColorModel().getTransparency();
        BufferedImage img;
        Graphics2D graphics2d;
        (graphics2d = (img = new BufferedImage(w, h, type))
                .createGraphics()).setRenderingHint(
                RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2d.setPaint(Color.WHITE);
        graphics2d.fillRect(0, 0, w, h);
        graphics2d.rotate(Math.toRadians(degree), w / 2, h / 2);
        graphics2d.drawImage(bufferedimage, 0, 0, Color.WHITE, null);
        graphics2d.dispose();
        return img;
    }
    
    
    /**
     * 合成分享图片
     * * @param bigPath 主图图片路径
     * * @param smallPath 商品图片路径 https://o.rjkj7.com/data/upload/images/2018-07-27/qymiyRvASErVPFLqIuVaGOLLYGLtXK.jpg
     * * @param erweimaPath 二维码图片路径
     *
     * @param title
     * @param productPrice
     * @param marketPrice
     * @param smallPath
     * @param erweimaPath
     */
    public static InputStream overlapImage(String title, double productPrice, double marketPrice,
                                           String smallPath, String erweimaPath, String desc,String unit,
                                           BigDecimal vipprice, List<String> labelList,String thumb) {
        try {
        	if(smallPath==null || smallPath.equals("")) {
        		smallPath = thumb;
        	}
            if (!smallPath.contains("http://") && !smallPath.contains("https://")) {
                smallPath = "https://o.rjkj7.com".concat(smallPath);
            }

            URL url = new URL("https://o.rjkj7.com/data/upload/images/2019-01-30/62360689e7b2bc10c637cb3bc995aacb.jpg");
            BufferedImage big = ImageIO.read(url.openStream());
          
            URL sUrl = new URL(smallPath);
            BufferedImage small = ImageIO.read(sUrl.openStream());
            
            int width = 540;
            int height = 900;
            Image image = big.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage bufferedImage2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
            Graphics2D g = bufferedImage2.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//消除文字锯齿
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//消除图像锯齿
            int sw = 520;
            int sh = (int) Math.min((float)small.getHeight() / (float)small.getWidth() * (float)sw, 300);
            int x = (width - sw) / 2;
            int y = 150;

            g.drawImage(image, 0, 0, null);
            //商品首图
            g.drawImage(small, 90, 120, 350, 350, null);
            Path path = FileSystems.getDefault().getPath("font","yuanti.ttc");
            Font stFont = Font.createFont(Font.TRUETYPE_FONT, new File(path.toUri()));

            g.setFont(stFont.deriveFont(Font.BOLD, 26));
            //g.setFont(new Font("微软雅黑", Font.BOLD, 26));
            int numWidth = x + 5;
            int numHeight =  sh + y + 100;
            g.setPaint(Color.black);
            if(labelList.size()>0) {
            	for (String str : labelList) {
            		title = str+title;
				}
            }else {
            	title = "[热销]"+title;
            }
            if(title.contains("(") || title.contains("（")) {
    			title = title.replace("(", ",");
    		}
    		if(title.contains(")")  || title.contains("）")) {
    			title = title.replace(")", ".");
    		}
            //标题1
            if(title.length()>18) {
                     String [] strList = title.split(" ");
                     String titleOne = "";
                     String titletwo = "";
                     if(strList.length>2) {
                    	  titleOne = strList[0];
                          titletwo = strList[1]; 
                     }else {
                    	 titletwo = title.substring(title.length()-(title.length()-16));
                    	 String [] titleStr = title.split(titletwo);
                    	 titletwo =  titletwo.replace(",", "(");
                    	 titletwo = titletwo.replace(".", ")");
                    	 if(titleStr.length>0) {
                    		 titleOne = titleStr[0];
                    	 }
                    	
                     }
                     if(titleOne.length()>18) {
                    	 String str = titleOne.substring(titleOne.length()-(titleOne.length()-16));
                    	 titletwo = str.concat(" ").concat(titletwo);
                    	 String [] titleList = titleOne.split(str);
                    	 titleOne = titleList[0];
                    	 titletwo =  titletwo.replace(",", "(");
                    	 titletwo = titletwo.replace(".", ")");
                     }
                     /*numHeight += drawString(g, titleOne, 30, sw, 110, numWidth+80, numHeight-35);
                     numHeight += drawString(g, titletwo, 30, sw, 110, numWidth+80, numHeight-20);*/
                     numHeight += drawString(g, titleOne, 30, sw, 110, numWidth+82, numHeight-35);
                     numHeight += drawString(g, titletwo, 30, sw, 110, numWidth+82, numHeight-20);
            }else {
            	 String str = "//";
            	 //numHeight += drawString(g, title, 30, sw, 110, numWidth+65, numHeight-35);
            	 numHeight += drawString(g, title, 30, sw, 110, numWidth+66, numHeight-35);
            	 g.setPaint(Color.white);
            	 //numHeight += drawString(g,  str,30, sw, 110, numWidth+65, numHeight-20);
            	 numHeight += drawString(g,  str,30, sw, 110, numWidth+66, numHeight-20);
            }
           
            numHeight += 20;
            g.setFont(stFont.deriveFont(Font.BOLD, 30));
            //g.setFont(new Font("微软雅黑", Font.BOLD, 30));
            g.setColor(new Color(0xdf0f18));
            int priceWidth = g.getFontMetrics().stringWidth("¥" + marketPrice);
            int priceHeight = g.getFontMetrics().getHeight();
            int baseline = g.getFontMetrics().getAscent();
            g.drawString("¥"+ marketPrice+"/"+unit, 200 , numHeight-30);
            
            g.setFont(stFont.deriveFont(Font.BOLD, 24));
            //g.setFont(new Font("微软雅黑", Font.BOLD, 24));
            g.setPaint(Color.GRAY);
            AttributedString as = new AttributedString("¥" + productPrice);
            as.addAttribute(TextAttribute.FONT, g.getFont());
            as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
            g.drawString(as.getIterator(), 200 + 50 + priceWidth,numHeight-30);
      
          
            
           g.setFont(stFont.deriveFont(Font.BOLD, 20));
           //g.setFont(new Font("微软雅黑", Font.BOLD, 20));
            g.setColor(new Color(0xdf0f18));
            baseline = g.getFontMetrics().getAscent();
            g.setColor(Color.white);
           // g.drawString(desc, 205 , numHeight + priceHeight+ baseline -37);
            g.drawString(desc, 205 , 655);
            if (StringUtils.isNotEmpty(erweimaPath)) {
                if (!erweimaPath.contains("https://") && !erweimaPath.contains("https://")) {
                    erweimaPath = "https://o.rjkj7.com".concat(erweimaPath);
                }
                URL eUrl = new URL(erweimaPath);
                BufferedImage erweima = ImageIO.read(eUrl.openStream());
              //二维码
               // g.drawImage(erweima, 50, numHeight+90, 170, 170, null);
                g.drawImage(erweima, 50, 720, 170, 170, null);
            }
            g.dispose();
            return getImageStream(bufferedImage2);
        } catch (Exception e) {
        	logger.info("check output err:",e);
            e.printStackTrace();
        }
        return null;
    }
    

    public static InputStream getImageStream(BufferedImage destImg) {
        InputStream is = null;
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imOut = null;
        try {
            imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(destImg, "png", imOut);
            is = new ByteArrayInputStream(bs.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
 			try {
 				if (is != null) {
 					is.close();
 				}
 				if (bs != null) {
 					bs.close();
 				}
 				if (imOut != null) {
 					imOut.close();
 				}
			} catch (Exception e) {

				e.printStackTrace();
			}
		}
        return is;
    }

    public static File createQrFile(String text,Integer width, Integer height){
        try {
            Map<EncodeHintType,Object> config = new HashMap<>(4);
            config.put(EncodeHintType.CHARACTER_SET,"UTF-8");
            config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            config.put(EncodeHintType.MARGIN, 0);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE,width,height,config);
            String fileName = CommonUtils.getSn("qr_");
            Path path = FileSystems.getDefault().getPath("upload",fileName+".png");
            //Path path = FileSystems.getDefault().getPath("D:\\",fileName+".png");
            MatrixToImageWriter.writeToPath(bitMatrix,"png",path);
            return path.toFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static float drawString(Graphics2D g, String text, float lineHeight
            , float maxWidth, int maxLine, float left, float top) {
        if (text == null || text.length() == 0) return 0;
        float textHeight = lineHeight;
        FontMetrics fm = g.getFontMetrics();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            sb.append(c);
            int stringWidth = fm.stringWidth(sb.toString());
            if (c == '\n' || stringWidth > maxWidth) {
                if(c == '\n') {
                    i += 1;
                }
                if (maxLine > 1) {
                    g.drawString(text.substring(0, i), left, top);
                    textHeight += drawString(g, text.substring(i), lineHeight, maxWidth
                            , maxLine - 1, left, top + lineHeight);
                } else {
                    g.drawString(text.substring(0, i - 1) + "…", left, top);
                }
                return textHeight;
            }
        }
        g.drawString(text, left, top);
        return textHeight;
    }
    
    
    /**
     * 合成分享图片
     * * @param bigPath 主图图片路径
     * * @param smallPath 商品图片路径 https://o.rjkj7.com/data/upload/images/2018-07-27/qymiyRvASErVPFLqIuVaGOLLYGLtXK.jpg
     * * @param erweimaPath 二维码图片路径
     *
     */
    public static InputStream sharelapImage( List<OrderProduct> list) {
        try {
        	if(list.isEmpty()) {
        		return null;
        	}

            URL url = new URL("https://o.rjkj7.com/data/upload/images/2019-06-27/16f0cdff8caaad068dcdda6a37fc715d.png");
            BufferedImage big = ImageIO.read(url.openStream());


            int width = 468;
            int height = 376;
            Image image = big.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage bufferedImage2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
            Graphics2D g = bufferedImage2.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//消除文字锯齿
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//消除图像锯齿

            g.drawImage(image, 0, 0, null);

            //g.setFont(stFont.deriveFont(Font.BOLD, 26));
            g.setFont(new Font("微软雅黑", Font.BOLD, 26));
            int numWidth =  50;
            int numHeight = 50;
            g.setPaint(Color.black);

            int num = 50;
            numHeight += 20;
            for (int i = 0; i < list.size(); i++) {

            	   if(i>=3) {
                 	  break;
                   }
            	   Path path = FileSystems.getDefault().getPath("font","yuanti.ttc");
                   Font stFont = Font.createFont(Font.TRUETYPE_FONT, new File(path.toUri()));

                   g.setFont(stFont.deriveFont(Font.BOLD, 25));
            	//  g.setFont(new Font("微软雅黑", Font.BOLD, 25));
                  g.setPaint(Color.black);
                 /* int priceWidth = g.getFontMetrics().stringWidth("¥" + "///");
                  int priceHeight = g.getFontMetrics().getHeight();
                  int baseline = g.getFontMetrics().getAscent();*/
                 if( list.get(i).getShortTitle().length()>9) {
                	 g.drawString(list.get(i).getShortTitle().substring(0,9), 60 , numHeight+num);
                 }else {
                	 g.drawString(list.get(i).getShortTitle(), 60 , numHeight+num);
                 }

                 g.setFont(stFont.deriveFont(Font.BOLD, 25));
                  //g.setFont(new Font("微软雅黑", Font.BOLD, 25));
                  g.setColor(new Color(0xdf0f18));
                  g.drawString("省"+list.get(i).getProductprice().subtract(list.get(i).getMarketprice()) +"元", 300 , numHeight+num);

                  num += 60;
			}

            BigDecimal productprice = list.stream().map(OrderProduct::getProductprice).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal marketprice = list.stream().map(OrderProduct ::getMarketprice).reduce(BigDecimal.ZERO, BigDecimal::add);
            g.setFont(new Font("微软雅黑", Font.BOLD, 25));
            g.setColor(new Color(0xdf0f18));
            g.drawString( "  "+productprice.subtract(marketprice)+"   "+"元", 240 , numHeight+275);

            g.dispose();
            return getImageStream(bufferedImage2);
        } catch (Exception e) {
        	logger.info("check output err:",e);
            e.printStackTrace();
        }
        return null;
    }

}
